package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ListView;

import com.auto.learning.R;
import com.auto.learning.adapter.PlayListAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SelectionVo;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.LoginSuccessEvent;
import com.auto.learning.event.ProgressEvent;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.DownLoadManager;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

/**
 * 播放列表
 * @author wangjianjun
 */
public class PlayListActivity extends BaseActivity {
	
	private ListView play_listview;
	private PlayListAdapter adapter;
	private ArrayList<BookBean> list = new ArrayList<BookBean>();
	private ProgressEvent progress = new ProgressEvent();
	
	private Handle handler = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GET_LOCAL_BOOKBEAN_SUCCESS:
				BookBean bean = (BookBean) msg.obj;
				if (bean != null) {
					for (int i = 0; i < list.size(); i++) {
						if (list.get(i).getBookId() == bean.getBookId()) {
							list.get(i).setBookName(bean.getBookName());
							break;
						}
					}
					if (adapter != null) {
						adapter.notifyDataSetChanged();
					}
				}
				break;
			case 1:
				ProgressEvent event = (ProgressEvent) msg.obj;
				if (event != null) {
					progress.setBookId(event.getBookId());
				    progress.setCurrentRatio(event.getCurrentRatio());
				    handler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							if (adapter != null) {
								adapter.notifyDataSetChanged();
							}
						}
					}, 500);
				}
				break;
			case 2:
				BookBean bookBean = (BookBean) msg.obj;
				if (bookBean != null) {
					if (!TemporaryVariable.downLoadedList.contains(bookBean.getBookId())) {
						if (!TemporaryVariable.temp_download_all_list.contains(bookBean.getBookId())) {
							if (CommonMethod.checkUserLogin(PlayListActivity.this)) {
								DownLoadManager.getInstance(PlayListActivity.this).setContext(PlayListActivity.this).prepareBefore(bookBean.getBookId(),bookBean.getProSize() + bookBean.getDoubiSize() + bookBean.getEnSize());
								
							}
						}
					}
				}
				break;
			case 3:
				final int bookId = (int) msg.obj;
				int ids[] = MusicPlayManager.getInstance(PlayListActivity.this).isPlayingBookId();
				if (bookId == ids[0]) {
					MusicPlayManager.getInstance(PlayListActivity.this).pause();
				}else {
					if (!TemporaryVariable.downLoadedList.contains(bookId)) {
						int flag = CommonMethod.getNetworkState(PlayListActivity.this);
						switch (flag) {
						case 0:
							CommonMethod.makeNotice(PlayListActivity.this, getResources().getString(R.string.connect_err_io));
							break;
						case 1:
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									MusicPlayManager.getInstance(PlayListActivity.this).setBookId(bookId).play();
								}
							}, 1000);
							break;
						case 2:
							String[] a = {"继续","取消"};
							String message = getResources().getString(R.string.text_no_wifi);
							int position = msg.arg1;
							if (position > 0) {
								BookBean m_BookBean =  list.get(position);
								int allSize= m_BookBean.getProSize() + m_BookBean.getDoubiSize() + m_BookBean.getEnSize();
								message = allSize > 0 ? String.format(getResources().getString(R.string.download_notice), CommonMethod.calculationNum(allSize)) : getResources().getString(R.string.text_no_wifi);
							}
							CommonMethod.showDialog(PlayListActivity.this,a, message, new DialogListener() {
								
								@Override
								public void otherButtonClick(Dialog dialog) {
									dialog.dismiss();
								}
								
								@Override
								public void okButtonClick(Dialog dialog) {
									dialog.dismiss();
									handler.postDelayed(new Runnable() {
										@Override
										public void run() {
											MusicPlayManager.getInstance(PlayListActivity.this).setBookId(bookId).play();
										}
									}, 1000);
								}
								
								@Override
								public void cancelButtonClick(Dialog dialog) {
									dialog.dismiss();
								}
							});
							break;
						}
					}else {
						handler.postDelayed(new Runnable() {
							@Override
							public void run() {
								MusicPlayManager.getInstance(PlayListActivity.this).setBookId(bookId).play();
							}
						}, 1000);
					}
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_SUCCESS:
				CommonMethod.makeNotice(PlayListActivity.this, "登录成功");
				ResponeResult login_result = (ResponeResult) msg.obj;
				if(login_result != null){
					EventBus.getEventBus("login_success_refreshUI").post(login_result);
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_FAIL:
				CommonMethod.makeNotice(PlayListActivity.this, msg.obj.toString());
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.play_list_activity);
		initData();
		initView();
		registerEvent();
		TemporaryVariable.activities.push(this);
	}
	public void initData(){
		ArrayList<BookBean> tempList = MusicPlayManager.getInstance(this).getPlayList();
		if (tempList != null && tempList.size() > 0) {
			list.addAll(tempList);
		}
		if (list != null && list.size() == 1 && TextUtils.isEmpty(list.get(0).getBookName())) {
			Cache.getBookBeanById(this, list.get(0).getBookId(), handler);
		}
	}
	
	public void initView(){
		setTitle("播放列表");
		hideRight();
		play_listview = (ListView) findViewById(R.id.play_listview);
		adapter = new PlayListAdapter(this, list, handler,progress);
		play_listview.setAdapter(adapter);
	}
	
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}
	
	@Subscribe
	public void onEventProgress(ProgressEvent event){
		handler.obtainMessage(1, event).sendToTarget();
	}
	
	public void registerEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("downloadProgress",ThreadEnforcer.MAIN).register(this);
	}
	
	public void unRegisterEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("downloadProgress",ThreadEnforcer.MAIN).unregister(this);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && resultCode == 203 && data != null) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					HttpRequestHelper.login2(PlayListActivity.this,data.getStringExtra("userId"), data.getStringExtra("nickName"),
							data.getStringExtra("headImgUrl"), data.getBooleanExtra("isweixin",false), handler);
				}
			});
		}else if (requestCode == 100 && resultCode == 204) {
			EventBus.getEventBus("login_refreshUI").post(new LoginSuccessEvent());
		}
	}
	
	@Override
	protected void onDestroy() {
		TemporaryVariable.activities.removeElement(this);
		unRegisterEvent();
		super.onDestroy();
	}
}
